/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tritonus.share.sampled.file.TAudioFileFormat;
import service.Audio;
import service.AudioFacadeREST;
import service.Planet;
import service.PlanetFacadeREST;
import service.Video;
import service.VideoFacadeREST;

/**
 *
 * @author andrew
 */
public class UploadAudioVideoServlet extends HttpServlet {

    @EJB
    private PlanetFacadeREST planetManager;
    @EJB
    private AudioFacadeREST audioManager;
    @EJB
    private VideoFacadeREST videoManager;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    // <editor-fold desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist


        System.out.println("request.getParameter delfile: " + request.getParameter("delfile"));

//        HttpSession session = request.getSession();

        Integer universe_id = (Integer) session.getAttribute("idUniverse");
        Integer planet_id = (Integer) session.getAttribute("idPlanet");

        Integer happiness_session = Integer.parseInt(request.getParameter("happiness")); // viene passato il valore di happiness ogni volta
        System.out.println("$$$Upload Servlet AUDIOVIDEO GET settato happiness a: " + happiness_session);

        boolean happiness;

        if (happiness_session == 1) {
            happiness = true;
        } else {
            happiness = false;
        }


        if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
            String pathFile = "";

            String labelGet = request.getParameter("getfile").substring(request.getParameter("getfile").lastIndexOf("/") + 1);
            String newFileGet = request.getParameter("getfile").substring(0, request.getParameter("getfile").lastIndexOf("/"));

            if (labelGet.equals("audio")) {
                pathFile = request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/audio/" + newFileGet;
            } else {
                pathFile = request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/video/" + newFileGet;
            }
            File file = new File(pathFile);
            if (file.exists()) {
                int bytes = 0;
                ServletOutputStream op = response.getOutputStream();

                response.setContentType(getMimeType(file));
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "inline; filename=\"" + newFileGet + "\"");

                File f = new File(request.getServletContext().getRealPath("/") + File.separator + "Universes/" + universe_id + labelGet);
                //System.out.print("prrr000");
                byte[] bbuf = new byte[1024];
                DataInputStream in = new DataInputStream(new FileInputStream(file));

                while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                    op.write(bbuf, 0, bytes);
                }

                in.close();
                op.flush();
                op.close();

            }
        } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {

            String newDelFileDel = request.getParameter("delfile").substring(request.getParameter("delfile").lastIndexOf("/") + 1);
            System.out.println("valore newDelFileDel = " + newDelFileDel);

            String labelDel = newDelFileDel.substring(newDelFileDel.lastIndexOf("."));
            System.out.println("valore labelDel = " + labelDel);


            String pathFile = "";
            Planet planet = planetManager.find(planet_id);

            if (labelDel.equals(".mp3")) {
                pathFile = request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/audio/" + newDelFileDel;
                //cancellazione in lista e in db
                Collection<Audio> collAudio = planet.getAudioCollection();
                Iterator iteratorAudio = collAudio.iterator();
                while (iteratorAudio.hasNext()) {
                    Audio audio = (Audio) iteratorAudio.next();
                    iteratorAudio.remove();
                    audioManager.remove(audio);
                    break;
                }
                planet.setAudioCollection(collAudio);
                planetManager.edit(planet);

            } else if (labelDel.equals(".mp4")) {
                pathFile = request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/video/" + newDelFileDel;

                //cancellazione in lista e in db
                Collection<Video> collVideo = planet.getVideoCollection();
                Iterator iteratorVideo = collVideo.iterator();
                while (iteratorVideo.hasNext()) {
                    Video video = (Video) iteratorVideo.next();
                    iteratorVideo.remove();
                    videoManager.remove(video);
                    break;
                }
                planet.setVideoCollection(collVideo);
                planetManager.edit(planet);

            }

            System.out.println("PathFile = " + pathFile);
            File file = new File(pathFile);
            if (file.exists()) {
                file.delete();
            }


        } else {
            // lista di file già presenti sul server
            response.setContentType("application/json");
            JSONArray json = new JSONArray();

            String JsonNameFile = null;
            String JsonUrl = null;
            String JsonDelFile = null;

            boolean canResponse = false;

            Planet currentPlanet = planetManager.find(planet_id);
            Collection<Audio> collAudio = currentPlanet.getAudioCollection();
            Collection<Video> collVideo = currentPlanet.getVideoCollection();

            if (!collAudio.isEmpty()) {
                Iterator<Audio> itCollAudio = collAudio.iterator();
                while (itCollAudio.hasNext()) {
                    Audio a = itCollAudio.next();
                    if (a.getIsHappy() == happiness) {
                        JsonNameFile = a.getPathAudio();
                        JsonNameFile = JsonNameFile.substring(JsonNameFile.lastIndexOf("/") + 1);
                        JsonUrl = "UploadAudioVideoServlet?happiness=" + happiness_session + "&getfile=" + JsonNameFile;
                        JsonDelFile = "UploadAudioVideoServlet?happiness=" + happiness_session + "&delfile=" + JsonNameFile;
                        canResponse = true;
                    }
                }

            }

            if (!collVideo.isEmpty()) {
                Iterator<Video> itCollVideo = collVideo.iterator();
                while (itCollVideo.hasNext()) {
                    Video v = itCollVideo.next();
                    if (v.getIsHappy() == happiness) {
                        JsonNameFile = v.getPathVideo();
                        JsonNameFile = JsonNameFile.substring(JsonNameFile.lastIndexOf("/") + 1);
                        JsonUrl = "UploadAudioVideoServlet?happiness=" + happiness_session + "&getfile=" + JsonNameFile;
                        JsonDelFile = "UploadAudioVideoServlet?happiness=" + happiness_session + "&delfile=" + JsonNameFile;
                        canResponse = true;
                    }
                }
            }

            if (canResponse) {
                try {
                    JSONObject jsono = new JSONObject();
                    jsono.put("name", JsonNameFile);
                    jsono.put("url", JsonUrl);
                    jsono.put("delete_url", JsonDelFile);
                    jsono.put("delete_type", "GET");
                    json.put(jsono);

                } catch (JSONException ex) {
                    Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

                response.getWriter().write(json.toString());
                canResponse = false;
            }



        }


    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //HttpSession session = request.getSession(); 

        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist


        boolean happy = true;

        // ottieni id Universo
        Integer universe_id = (Integer) session.getAttribute("idUniverse");
        Integer planet_id = (Integer) session.getAttribute("idPlanet");


        //  prendo pianeta con id = planet_id
        Planet currentPlanet = planetManager.find(planet_id);

        // prendere la audiocollection associata 
        Collection<Audio> collAudio = currentPlanet.getAudioCollection();

        // prendere la videocollection associata 
        Collection<Video> collVideo = currentPlanet.getVideoCollection();

        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());

        List<FileItem> items;
        PrintWriter writer = response.getWriter();
        response.setContentType("application/json");
        JSONArray json = new JSONArray();
        try {
            items = uploadHandler.parseRequest(request);

            for (FileItem item : items) {
                if (item.isFormField() && item.getFieldName().equals("happiness")) {
                    Integer happiness_session = Integer.parseInt(item.getString());

                    if (happiness_session == 1) {
                        happy = true;
                    } else {
                        happy = false;
                    }

                    System.out.println("$$$Upload Servlet AUDIOVIDEO POST settato " + item.getFieldName() + " a: " + happiness_session);
                    break;
                }
            }

            for (FileItem item : items) {
                if (!item.isFormField()) {

                    System.out.println("valore passato: " + item.getName());
                    System.out.println("Dim File: " + item.getSize());
                    System.out.println(item.getName().substring(item.getName().lastIndexOf(".")));
                    
                    List<Audio> listAudio = audioManager.findAll();
                    Iterator<Audio> audioIt = listAudio.iterator();
                    Audio tmpa = null;
                    int idAudioForDB = -1;
                    while (audioIt.hasNext()) {
                        tmpa = audioIt.next();
                        if (tmpa.getIdAudio() > idAudioForDB) {
                            idAudioForDB = tmpa.getIdAudio();
                        }
                    }
                    idAudioForDB++;
                    
                     List<Video> listVideo = videoManager.findAll();
                     Iterator<Video> videoIt = listVideo.iterator();
                     Video tmpv = null;

                     int idVideoinDB = -1;


                    while (videoIt.hasNext()) {
                        tmpv = videoIt.next();
                        if (tmpv.getIdVideo() > idVideoinDB) {
                            idVideoinDB = tmpv.getIdVideo();
                        }
                    }

                    idVideoinDB++;
                    
                    int newIdMultimediainDB = idAudioForDB + idVideoinDB;
                    
                    
                    if (item.getName().substring(item.getName().lastIndexOf(".")).equals(".mp4")){
                        
                        if(item.getSize() <= 20000000) {
                            // aggiungo file video
                            System.out.println("VIDEO");

                            // aggiornamento video in db
                            currentPlanet = planetManager.find(planet_id);
                            // prendere la photocollection associata 
                            Collection<Video> collVideo1 = currentPlanet.getVideoCollection();
                            Collection<Audio> collAudioCheck = currentPlanet.getAudioCollection();

                            boolean canAdd = false;

                            if ((!collVideo1.isEmpty()) && (collAudioCheck.isEmpty())) {
                                Iterator iteratorVideo = collVideo1.iterator();
                                while (iteratorVideo.hasNext()) {
                                    Video tmpVideo = (Video) iteratorVideo.next();
                                    if (tmpVideo.getIsHappy() != happy) {
                                        canAdd = true;
                                    }
                                }
                            } else if ((collVideo1.isEmpty()) && (!collAudioCheck.isEmpty())) {
                                Iterator iteratorAudio = collAudioCheck.iterator();
                                while (iteratorAudio.hasNext()) {
                                    Audio tmpAudio = (Audio) iteratorAudio.next();
                                    if (tmpAudio.getIsHappy() != happy) {
                                        canAdd = true;
                                    }
                                }
                            }

                            if ((collVideo1.isEmpty() && collAudioCheck.isEmpty()) || (canAdd)) {

//                                List<Video> listVideo = videoManager.findAll();
//                                Iterator<Video> videoIt = listVideo.iterator();
//                                Video tmpVideo = null;
//
//                                int idVideoinDB = -1;
//
//                                while (videoIt.hasNext()) {
//                                    tmpVideo = videoIt.next();
//                                    if (tmpVideo.getIdVideo() > idVideoinDB) {
//                                        idVideoinDB = tmpVideo.getIdVideo();
//                                    }
//                                }
//
//                                idVideoinDB++;

                                String newName = "m" + universe_id + newIdMultimediainDB + ".mp4";

                                File file = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/video/", item.getName());

                                System.out.println("QQQ1: " + item.getName());

                                int happyParameter = -1;

                                if (happy) {
                                    happyParameter = 1;
                                } else {
                                    happyParameter = 0;
                                }


                                try {
                                    item.write(file);

                                    JSONObject jsono = new JSONObject();
                                    jsono.put("name", newName);
                                    jsono.put("size", item.getSize());
                                    jsono.put("url", "UploadAudioVideoServlet?happiness=" + happyParameter + "&getfile=" + item.getName());
                                    //jsono.put("thumbnail_url", "UploadAudioVideoServlet?getthumb=" + item.getName());
                                    jsono.put("delete_url", "UploadAudioVideoServlet?happiness=" + happyParameter + "&delfile=" + newName);
                                    jsono.put("delete_type", "GET");
                                    json.put(jsono);
                                } catch (Exception ex) {
                                    Logger.getLogger(UploadAudioVideoServlet.class.getName()).log(Level.SEVERE, null, ex);
                                }

                                System.out.println("inserisco video");
                                Video v = new Video();
                                v.setDescription(" ");
                                v.setIsHappy(happy);
                                v.setPathVideo(universe_id + "/video/" + newName);
                                v.setPlanetidPlanet(currentPlanet);
                                v.setTitle(" ");

                                collVideo1.add(v);

                                currentPlanet.setVideoCollection(collVideo1);

                                planetManager.edit(currentPlanet);

                                // rinomino file video appena inserito
                                if (!file.exists() || file.isDirectory()) {
                                    System.out.println("File does not exist: " + file);
                                    return;
                                }

                                File newFile = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName);

                                //Rename
                                if (file.renameTo(newFile)) {
                                    System.out.println("File has been renamed.");
                                } else {
                                    System.out.println("Error renaming file");
                                }
                            } else {
                                System.out.println("video non inserito");
                                if (!canAdd) {
                                    JSONObject jsonerror = new JSONObject();

                                    String htmlResponse = "<p class=\"text-center\">\n"
                                            + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il video:</span> <br /> <strong>si è raggiunto il numero massimo di file audio/video inseriti per il pianeta.</strong>\n"
                                            + "                            </p>\n"
                                            + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                            + "                            <ul>\n"
                                            + "                                <li>Non si può inserire più di un contenuto audio/video per pianeta.</li>\n"
                                            + "                            </ul>\n"
                                            + "                            </p>";

                                    jsonerror.put("error", htmlResponse);
    //                                    jsonerror.put("error", "Si è raggiunto il limite massimo di file audio/video consentito");
                                    json.put(jsonerror);
                                }
                            }
                            
                        }else{
                            // file troppo grande
                            JSONObject jsonerror = new JSONObject();

                                    String htmlResponse = "<p class=\"text-center\">\n"
                                            + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il video:</span> <br /> <strong>dimensione del file video troppo grande.</strong>\n"
                                            + "                            </p>\n"
                                            + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                            + "                            <ul>\n"
                                            + "                                <li>Il video deve avere una dimensione massima di <strong>20MB</strong>.</li>\n"
                                            + "                            </ul>\n"
                                            + "                            </p>";

                                    jsonerror.put("error", htmlResponse);
                                    json.put(jsonerror);
                        }
                        

                    } else if (item.getName().substring(item.getName().lastIndexOf(".")).equals(".mp3")) {
                        System.out.println("AUDIO");

                        boolean isMP3ok = false;

                        File file = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/audio/", item.getName());

                        try {
                            item.write(file);
                        } catch (Exception ex) {
                            Logger.getLogger(UploadAudioVideoServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        try {
                            isMP3ok = isMp3Acceptable(file);

                        } catch (UnsupportedAudioFileException ex) {
                            Logger.getLogger(UploadAudioVideoServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        if (isMP3ok) {
                            // aggiornamento audio in db
                            currentPlanet = planetManager.find(planet_id);
                            // prendere la photocollection associata 
                            Collection<Audio> collAudio1 = currentPlanet.getAudioCollection();
                            Collection<Video> collVideoCheck = currentPlanet.getVideoCollection();

                            boolean canAdd = false;

                            if ((!collAudio1.isEmpty()) && (collVideoCheck.isEmpty())) {
                                Iterator iteratorAudio = collAudio1.iterator();
                                while (iteratorAudio.hasNext()) {
                                    Audio tmpAudio = (Audio) iteratorAudio.next();
                                    if (tmpAudio.getIsHappy() != happy) {
                                        canAdd = true;
                                    }
                                }
                            } else if ((collAudio1.isEmpty()) && (!collVideoCheck.isEmpty())) {
                                Iterator iteratorVideo = collVideoCheck.iterator();
                                while (iteratorVideo.hasNext()) {
                                    Video tmpVideo = (Video) iteratorVideo.next();
                                    if (tmpVideo.getIsHappy() != happy) {
                                        canAdd = true;
                                    }
                                }
                            }

                            if ((collAudio1.isEmpty() && collVideoCheck.isEmpty()) || canAdd) {
                                System.out.println("inserisco audio");
                                System.out.println("QQQ2: " + item.getName());

//                                List<Audio> listAudio = audioManager.findAll();
//                                Iterator<Audio> audioIt = listAudio.iterator();
//                                Audio tmpAudio = null;
//                                int idAudioForDB = -1;
//                                while (audioIt.hasNext()) {
//                                    tmpAudio = audioIt.next();
//                                    if (tmpAudio.getIdAudio() > idAudioForDB) {
//                                        idAudioForDB = tmpAudio.getIdAudio();
//                                    }
//                                }
//
//                                idAudioForDB++;
                                
//                                System.out.println("idAudioForDB: "+idAudioForDB);
                                String newName = "m" + universe_id + newIdMultimediainDB + ".mp3";

                                int happyParameter;

                                if (happy) {
                                    happyParameter = 1;
                                } else {
                                    happyParameter = 0;
                                }

                                //File file = new File(request.getServletContext().getRealPath("/")+"Universes/"+universe_id+"/audio/"+item.getName());
                                //System.out.println("Vediamo cosa stampi: "+request.getServletContext().getRealPath("/")+"Universes/"+universe_id+"/audio/"+item.getName());
                                try {
                                    //item.write(file);
                                    JSONObject jsono = new JSONObject();
                                    jsono.put("name", newName);
                                    jsono.put("size", item.getSize());
                                    jsono.put("url", "UploadAudioVideoServlet?happiness=" + happyParameter + "&getfile=" + newName);
                                    //jsono.put("thumbnail_url", "UploadAudioVideoServlet?getthumb=" + newName);
                                    jsono.put("delete_url", "UploadAudioVideoServlet?happiness=" + happyParameter + "&delfile=" + newName);
                                    jsono.put("delete_type", "GET");
                                    json.put(jsono);
                                } catch (Exception ex) {
                                    Logger.getLogger(UploadAudioVideoServlet.class.getName()).log(Level.SEVERE, null, ex);
                                }

                                Audio a = new Audio();
                                a.setDescription(" ");
                                a.setIsHappy(happy);
                                a.setPathAudio(universe_id + "/audio/" + newName);
                                a.setPlanetidPlanet(currentPlanet);
                                a.setTitle(newName.substring(0, newName.lastIndexOf(".")));

                                collAudio1.add(a);

                                currentPlanet.setAudioCollection(collAudio1);

                                planetManager.edit(currentPlanet);

                                // rinomina file audio appena inserito
                                if (!file.exists() || file.isDirectory()) {
                                    System.out.println("File does not exist: " + file);
                                    return;
                                }




                                File newFile = new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName);

                                //Rename
                                if (file.renameTo(newFile)) {
                                    System.out.println("File has been renamed.");
                                } else {
                                    System.out.println("Error renmaing file");
                                }

                            } else {
                                System.out.println("audio non inserito");
                                if (!canAdd) {
                                    //System.out.println("Siamo al completo");
                                    JSONObject jsonerror = new JSONObject();

                                    String htmlResponse = "<p class=\"text-center\">\n"
                                            + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il file audio:</span> <br /> <strong>si è raggiunto il numero massimo di file audio/video inseriti per il pianeta.</strong>\n"
                                            + "                            </p>\n"
                                            + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                            + "                            <ul>\n"
                                            + "                                <li>Non si può inserire più di un contenuto audio/video per pianeta.</li>\n"
                                            + "                            </ul>\n"
                                            + "                            </p>";

                                    jsonerror.put("error", htmlResponse);

//                                    jsonerror.put("error", "Si è raggiunto il limite massimo di file audio/video consentito");
                                    json.put(jsonerror);
                                }

                            }
                        } else {
                            System.out.println("Il file audio supera i limiti consentiti");
                            try {
                                JSONObject jsonerror = new JSONObject();

                                String htmlResponse = "<p class=\"text-center\">\n"
                                        + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il file:</span> <br /> <strong>il contenuto audio inserito eccede la durata massima consentita.</strong>\n"
                                        + "                            </p>\n"
                                        + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                        + "                            <ul>\n"
                                            + "                                <li>Il contenuto audio inserito deve avere una durata inferiore a <strong>3 minuti</strong>.</li>\n"
                                        + "                            </ul>\n"
                                        + "                            </p>";

                                jsonerror.put("error", htmlResponse);

//                                jsonerror.put("error", "Il file audio supera i limiti consentiti");
                                json.put(jsonerror);

                                if (file.delete()) {
                                    System.out.println(file.getName() + " is deleted because it exceeded limit supported!");
                                } else {
                                    System.out.println("Delete operation is failed.");
                                }
                            } catch (Exception e) {
                            }
                        }

                    } else {
                        System.out.println("Formato del file inserito non corretto");
                        JSONObject jsonerror = new JSONObject();
                        
                        String htmlResponse = "<p class=\"text-center\">\n"
                            + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il file:</span> <br /> <strong>il formato non &egrave; supportato.</strong>\n"
                                + "                            </p>\n"
                                + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                + "                            <ul>\n"
                                + "                            <li>Se il file caricato è un <strong>audio</strong> deve essere in formato <strong>.mp3</strong></li>\n" +
"                                                              <li>Se il file caricato è un <strong>video</strong> deve essere in formato <strong>.mp4</strong></li>"
                                + "                            </ul>\n"
                                + "                            </p>";

                        jsonerror.put("error", htmlResponse);
                        
//                        jsonerror.put("error", "Formato del file inserito non corretto");
                        json.put(jsonerror);
                    }

                }
            }
        } catch (JSONException ex) {
            Logger.getLogger(UploadAudioVideoServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadAudioVideoServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            writer.write(json.toString());
            writer.close();
        }

//        }

    }

    private String getMimeType(File file) {
        String mimetype = "";
        if (file.exists()) {
            if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
                mimetype = "image/png";
            } else if (getSuffix(file.getName()).equalsIgnoreCase("jpg")) {
                mimetype = "image/jpg";
            } else if (getSuffix(file.getName()).equalsIgnoreCase("jpeg")) {
                mimetype = "image/jpeg";
            } else if (getSuffix(file.getName()).equalsIgnoreCase("gif")) {
                mimetype = "image/gif";
            } else {
                javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
                mimetype = mtMap.getContentType(file);
            }
        }
        return mimetype;
    }

    private String getSuffix(String filename) {
        String suffix = "";
        int pos = filename.lastIndexOf('.');
        if (pos > 0 && pos < filename.length() - 1) {
            suffix = filename.substring(pos + 1);
        }
        return suffix;
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean isMp3Acceptable(File file) throws UnsupportedAudioFileException, IOException {

        AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
        Map<?, ?> properties = ((TAudioFileFormat) fileFormat).properties();
        String key = "duration";
        Long microseconds = (Long) properties.get(key);
        int mili = (int) (microseconds / 1000);
        int sec = (mili / 1000) % 60;
        int min = (mili / 1000) / 60;
        System.out.println("timeMP3 = " + min + ":" + sec);
        if (min < 3) {
            return true;
        } else {
            return false;
        }
    }
}
